import { _path, _dirname, fs } from '../../mode/allapi'
import { AMessage, plugin } from '../../api/api'

export class rankting extends plugin {
  constructor() {
    super({
      dsc: '榜单',
      rule: [
        {
          reg: /^(#|\/)?(讨伐榜|群雄榜|富豪榜)$/,
          fnc: 'hulaorank'
        }
      ]
    })
  }
  async hulaorank(e: AMessage) {
    if (e.isGroup !== true) return false

    const bangdan = {
      '/讨伐': 'DungeonStorey',
      '/群雄': 'havecity',
      '/富豪': 'currency_num'
    }

    const displayMap = {
      '/讨伐': player => `${player.name}：${player.DungeonStorey}`,
      '/群雄': player => `${player.name}：${player.havecity}`,
      '/富豪': player => `${player.name}：${player.currency_num}`
    }

    try {
      const playerList = fs
        .readdirSync(_dirname + '/resources/data/player')
        .filter(file => file.endsWith('.json'))
        .map(file => {
          const playerData = JSON.parse(
            fs.readFileSync(
              _dirname + `/resources/data/player/${file}`,
              'utf-8'
            )
          )
          return {
            name: playerData.name,
            DungeonStorey: playerData.DungeonStorey || 0,
            havecity: playerData.havecity || 0,
            currency_num: playerData.currency_num || 0
          }
        })
      if (e.msg == '讨伐榜' || e.msg == '#讨伐榜') e.msg = '/讨伐榜'
      else if (e.msg == '群雄榜' || e.msg == '#群雄榜') e.msg = '/群雄榜'
      else if (e.msg == '富豪榜' || e.msg == '#富豪榜') e.msg = '/富豪榜'
      const didian = e.msg.replace('榜', '')

      if (bangdan[didian]) {
        playerList.sort((a, b) => b[bangdan[didian]] - a[bangdan[didian]])
        const topPlayers = playerList.slice(0, 10)
        const rankList = topPlayers.map(player => displayMap[didian](player))

        let category
        if (e.msg == '/讨伐榜') category = '讨伐'
        else if (e.msg == '/群雄榜') category = '群雄'
        else if (e.msg == '/富豪榜') category = '富豪'
        e.reply(`————${category}榜————\n${rankList.join('\n')}`)
      } else {
        e.reply('未找到匹配的排行榜类型')
      }
    } catch (error) {
      e.reply('生成排行榜时出现错误')
      console.error(error)
    }
    return false
  }
}
